package com.zjlanyun.eplus.view.tree;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.jb.barcode.BarcodeManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.ScreenUtils;
import com.blankj.utilcode.utils.SizeUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.greendao.DBHelper;
import com.zjlanyun.eplus.greendao.IrActWindow;
import com.zjlanyun.eplus.greendao.IrModel;
import com.zjlanyun.eplus.greendao.IrModelAccess;
import com.zjlanyun.eplus.greendao.IrModelAccessDao;
import com.zjlanyun.eplus.greendao.IrModelFields;
import com.zjlanyun.eplus.greendao.IrModelFieldsDao;
import com.zjlanyun.eplus.greendao.IrSearchFields;
import com.zjlanyun.eplus.greendao.IrSearchFieldsDao;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.ButtonUtils;
import com.zjlanyun.eplus.utils.SoundManager;
import com.zjlanyun.eplus.view.BaseActivity;
import com.zjlanyun.eplus.view.CaptureActivity;
import com.zjlanyun.eplus.view.form.FormActivity;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;

public class TreeActivity extends BaseActivity {

    private Intent intent;
    private int page = 1;
    private TreeAdapter treeAdapter;
    private ArrayList<HashMap<String, Object>> mList;
    private List<IrModelFields> irModelFieldsList;
    private IrModelFields irModelFieldsKey;
    private IrModel irModel;
    private boolean showLoading = true;
    private IrActWindow irActWindow;
    private IrModelAccess irModelAccess;
    private long act_id = 0;//窗口ID
    private long model_id = 0; //模型ID
    private boolean isLoading = true;

    private PopupWindow searchWindow;
    private LinearLayout search_layout;
    private Button btn_search, btn_cancel;
    private List<IrSearchFields> irSearchFieldsList;
    private HashMap<String, Object> searchValue;
    private ArrayList<HashMap<String, Object>> scanLog; //扫描记录
    private long curFieldId = 0; //当前扫描字段ID
    private HashMap<Long, Object> itemWidget; //字段ID对应的控件
    private HashMap<Long, IrSearchFields> fieldsMap; //字段map，初始化好的字段
    private boolean hasSearch = false; //是否有搜索功能

    private BarcodeManager scanManager;
    private boolean isPDA = false;
    private SoundManager soundManager;

    static final int REQUESTCODE_READ = 1;
    static final int REQUESTCODE_CREATE = 2;
    public final static int REQUESTCODE_CAMERA = 3;

    @Bind(R.id.ib_add) ImageButton ib_add;
    @Bind(R.id.lv) ListView lv;
    @Bind(R.id.srl) SwipeRefreshLayout srl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tree_activity);
        initBaseView();
        initView();
        getData();
        initPDA();
    }

    private void initView() {
        intent = getIntent();
        act_id = intent.getLongExtra("act_id", 0);
        model_id = intent.getLongExtra("model_id", 0);
        mList = new ArrayList<>();
        searchValue = new HashMap<>();
        scanLog = new ArrayList<>();
        itemWidget = new HashMap<>();
        fieldsMap = new HashMap<>();
        soundManager = new SoundManager(mContext);

        //获取搜索字段
        QueryBuilder<IrSearchFields> qbSearch = DBHelper.getDaoSession(mContext).getIrSearchFieldsDao().queryBuilder();
        qbSearch.where(IrSearchFieldsDao.Properties.Act_id.eq(act_id)).orderAsc(IrSearchFieldsDao.Properties.Sequence);
        irSearchFieldsList = qbSearch.list();
        if (irSearchFieldsList.size() > 0) {
            initSearchView();
        }

        //获取模型内的字段
        QueryBuilder<IrModelFields> qb = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
        qb.where(IrModelFieldsDao.Properties.Model_id.eq(model_id), IrModelFieldsDao.Properties.View_type.eq("tree")).orderAsc(IrModelFieldsDao.Properties.Sequence);
        irModelFieldsList = qb.list();
        //获取模型
        irModel = DBHelper.getDaoSession(mContext).getIrModelDao().load(model_id);

        treeAdapter = new TreeAdapter(mContext, mList, irModelFieldsList);
        lv.setAdapter(treeAdapter);

        //获取模型访问权限
        QueryBuilder<IrModelAccess> qb1 = DBHelper.getDaoSession(mContext).getIrModelAccessDao().queryBuilder();
        qb1.where(IrModelAccessDao.Properties.Model_id.eq(model_id));
        irModelAccess = qb1.list().get(0);

        //是否有创建权限
        if (irModelAccess.getPerm_create()) {
            ib_add.setVisibility(View.VISIBLE);
            ib_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!ButtonUtils.isFastDoubleClick(v.getId())) {
                        Intent intent = new Intent(mContext, FormActivity.class);
                        intent.putExtra("model_id", model_id);
                        intent.putExtra("action", "create");
                        intent.putExtra("act_id", act_id);
                        startActivityForResult(intent, REQUESTCODE_CREATE);
                    }
                }
            });
        }

        //删除权限
        if (irModelAccess.getPerm_unlink()) {
            longClick();
        }

        //读取视图
        irActWindow = DBHelper.getDaoSession(mContext).getIrActWindowDao().load(act_id);
        if (irActWindow.getView_mode().indexOf("form") != -1) {
            //获取主键字段
            QueryBuilder<IrModelFields> qb2 = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
            qb2.where(IrModelFieldsDao.Properties.Model_id.eq(model_id), IrModelFieldsDao.Properties.View_type.eq("tree"), IrModelFieldsDao.Properties.Primary_key.eq(1)).limit(1);
            if (qb2.list().size() > 0) {
                irModelFieldsKey = qb2.list().get(0);
                //判断是否有form视图
                itemClick();
            } else {
                ToastUtils.showShortToast("请设置主键字段");
            }
        }
        title.setText(irActWindow.getName());

        //下拉刷新
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }
        });

        //上滑加载更多
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (lv.getLastVisiblePosition() == mList.size() - 1 && !isLoading) {
                    getData();
                }
            }
        });
    }

    //初始化搜索视图
    private void initSearchView() {
        hasSearch = true;
        switchZoom();
        //搜索
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSearchWindow(v);
                switchZoom();
            }
        });
    }

    //切换搜索按钮的图片
    @SuppressWarnings("deprecation")
    private void switchZoom() {
        Drawable drawable;
        if (searchWindow != null && searchWindow.isShowing()) {
            drawable = getResources().getDrawable(R.drawable.ic_zoom_out_black_24dp);
        } else {
            drawable = getResources().getDrawable(R.drawable.ic_zoom_in_black_24dp);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        title.setCompoundDrawables(drawable, null, null, null);
    }

    //显示搜索视图
    @SuppressWarnings("deprecation")
    private void showSearchWindow(View parent) {
        cleanScanLog();
        if (searchWindow == null) {
            int height = 0;
            View view = LayoutInflater.from(mContext).inflate(R.layout.search_window, null);
            btn_search = (Button) view.findViewById(R.id.btn_search);
            btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
            search_layout = (LinearLayout) view.findViewById(R.id.search_layout);

            for (int i = 0; i < irSearchFieldsList.size(); i++) {
                final IrSearchFields irSearchFields = irSearchFieldsList.get(i);
                height += 34;
                View item = LayoutInflater.from(mContext).inflate(R.layout.form_activity_item_1col, null);
                TextView tv_title = (TextView) item.findViewById(R.id.tv_title);
                tv_title.setText(irSearchFields.getField_desc());
                AutoCompleteTextView at_text = (AutoCompleteTextView) item.findViewById(R.id.at_text);
                at_text.setVisibility(View.VISIBLE);
                itemWidget.put(irSearchFields.getId(), at_text);
                fieldsMap.put(irSearchFields.getId(), irSearchFields); //加入到全局字段hashmap中
                searchValue.put(irSearchFields.getName(), "");
                search_layout.addView(item);
                at_text.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        searchValue.put(irSearchFields.getName(), s.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
                //监听扫描按钮
                at_text.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (irSearchFields.getScan()) {
                            if (keyCode == 139 && event.getRepeatCount() == 0) {
                                buttonScan();
                                return false;
                            }
                        }
                        return false;
                    }
                });
                //扫描
                if (irSearchFields.getScan()) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("scan", false);
                    map.put("field_id", irSearchFields.getId());
                    scanLog.add(map);

                    Button btn_scan = (Button) item.findViewById(R.id.btn_scan);
                    btn_scan.setVisibility(View.VISIBLE);
                    btn_scan.setTag(irSearchFields.getId());
                    btn_scan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            curFieldId = (long) v.getTag();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                checkCameraPermission();
                            } else {
                                openScan();
                            }
                        }
                    });
                }
            }
            searchWindow = new PopupWindow(view, ScreenUtils.getScreenWidth(), SizeUtils.dp2px(height + 62));
        }
        searchWindow.setFocusable(true);
        searchWindow.setOutsideTouchable(true);
        searchWindow.setBackgroundDrawable(new BitmapDrawable());
        searchWindow.showAsDropDown(parent, 0, 0);
        searchWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                switchZoom();
            }
        });

        //搜索
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSearch();
            }
        });

        //取消
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchWindow.dismiss();
            }
        });
    }

    //搜索开始
    private void startSearch(){
        showLoading = true;
        page = 1;
        mList = new ArrayList<>();
        treeAdapter = new TreeAdapter(mContext, mList, irModelFieldsList);
        lv.setAdapter(treeAdapter);
        getData();
        searchWindow.dismiss();
    }

    //获取数据
    private void getData() {
        isLoading = true;
        if (irModelFieldsList.size() == 0) {
            ToastUtils.showShortToast("没有配置字段");
            return;
        }
        HashMap<String, Object> param = new HashMap<>();
        param.put("searchValue", JSON.toJSONString(searchValue));
        param.put("page", page);
        param.put("model_id", model_id);
        param.put("act_id", act_id);
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getTree", JSON.toJSONString(param), true, showLoading);
        showLoading = false;
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                try {
                    if (page == 1)
                        mList.clear();
                    JSONArray list = response.get().getJSONObject("data").getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject item = list.getJSONObject(i);
                        HashMap<String, Object> map = new HashMap<>();
                        for (int j = 0; j < irModelFieldsList.size(); j++) {
                            map.put(irModelFieldsList.get(j).getName(), item.get(irModelFieldsList.get(j).getName()));
                        }
                        mList.add(map);
                    }
                    page++;
                    treeAdapter.notifyDataSetChanged();
                    srl.setRefreshing(false);
                    if (page >= response.get().getJSONObject("data").getInt("pageCount")) {
                        isLoading = true;
                    } else {
                        isLoading = false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //点击事件，打开form视图
    private void itemClick() {
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!ButtonUtils.isFastDoubleClick(position)) {
                    Intent intent = new Intent(mContext, FormActivity.class);
                    if (irModelFieldsKey.getTtype().equals("int")) {
                        intent.putExtra(irModelFieldsKey.getName(), String.valueOf(mList.get(position).get(irModelFieldsKey.getName())));
                    } else if (irModelFieldsKey.getTtype().equals("string")) {
                        intent.putExtra(irModelFieldsKey.getName(), (String) mList.get(position).get(irModelFieldsKey.getName()));
                    } else {
                        ToastUtils.showShortToast("主键只能是int或string类型");
                        return;
                    }
                    intent.putExtra("model_id", model_id);
                    intent.putExtra("action", "read");
                    intent.putExtra("act_id", act_id);
                    intent.putExtra("key_name", irModelFieldsKey.getName());
                    startActivityForResult(intent, REQUESTCODE_READ);
                }
            }
        });
    }

    //长按，删除
    private void longClick() {
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final int index = position;
                new AlertView("提示", "确定删除吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            HashMap<String, Object> param = new HashMap<>();
                            param.put("model_id", model_id);
                            param.put("key_name", irModelFieldsKey.getName());
                            param.put("key_value", mList.get(index).get(irModelFieldsKey.getName()));
                            HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "unlink", JSON.toJSONString(param), true, true);
                            httpRequest.send(new SimpleHttpListener<JSONObject>() {
                                @Override
                                public void onSucceed(int what, Response<JSONObject> response) {
                                    super.onSucceed(what, response);
                                    ToastUtils.showShortToast("删除成功");
                                    mList.remove(index);
                                    treeAdapter.notifyDataSetChanged();
                                }
                            });
                        }
                    }
                }).show();
                return true;
            }
        });
    }

    //初始化PDA
    private void initPDA() {
        //判断是否为PDA
        String deviceModel = Build.MODEL;
        if (deviceModel.length() > 5) {
            if (deviceModel.substring(0, 5).equals("HT380")) {
                isPDA = true;
                scanManager = BarcodeManager.getInstance();
                scanManager.Barcode_Open(mContext, new BarcodeManager.Callback() {
                    @Override
                    public void Barcode_Read(byte[] bytes, String s, int i) {
                        soundManager.playSound();
                        getScanResult(new String(bytes));
                    }
                });
            }
        }
    }

    //实体键启动扫描
    private void buttonScan() {
        if (searchWindow != null && searchWindow.isShowing()) {
            if (scanLog.size() > 0) {
                curFieldId = (long) scanLog.get(0).get("field_id");
                for (int i = 0; i < scanLog.size(); i++) {
                    if (!(boolean) scanLog.get(i).get("scan")) {
                        curFieldId = (long) scanLog.get(i).get("field_id");
                        break;
                    }
                }
                openScan();
            }
        }
    }

    //得到扫描结果
    private void getScanResult(String code) {
        IrSearchFields field = fieldsMap.get(curFieldId);
        AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(field.getId());
        actv.setText(code);
        if (scanLog.size() > 0) {
            int i;
            for (i = 0; i < scanLog.size(); i++) {
                if ((long) scanLog.get(i).get("field_id") == curFieldId) {
                    scanLog.get(i).put("scan", true);
                    break;
                }
            }
            if (i == scanLog.size() - 1) {
                cleanScanLog();
            }
        }
        //自动提交
        if (field.getAuto_submit()) {
            startSearch();
        }
    }

    /**
     * 清除扫描记录
     */
    private void cleanScanLog() {
        for (int i = 0; i < scanLog.size(); i++) {
            scanLog.get(i).put("scan", false);
        }
    }

    /**
     * 检查相机权限
     */
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            openScan();
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtils.showLongToast("请授权，否则无法扫描");
            }
            //申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //android6.0权限检查，重新启动扫描
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openScan();
            } else {
                ToastUtils.showShortToast("拒绝授权");
            }
        }
    }

    //打开扫描界面扫描条形码或二维码
    private void openScan() {
        if (!ButtonUtils.isFastDoubleClick((int) curFieldId)) {
            if (isPDA) {
                scanManager.Barcode_Start();
            } else {
                Intent openCameraIntent = new Intent(mContext, CaptureActivity.class);
                openCameraIntent.putExtra("from", TreeActivity.class.getName());
                startActivityForResult(openCameraIntent, REQUESTCODE_CAMERA);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUESTCODE_CREATE || requestCode == REQUESTCODE_READ) && resultCode == RESULT_OK) {
            srl.setRefreshing(true);
            page = 1;
            mList = new ArrayList<>();
            treeAdapter = new TreeAdapter(mContext, mList, irModelFieldsList);
            lv.setAdapter(treeAdapter);
            getData();
        } else if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK && data != null) {
            //扫码结果
            getScanResult(data.getStringExtra("result"));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (hasSearch && keyCode == 139 && event.getRepeatCount() == 0) {
            showSearchWindow(title);
            switchZoom();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
